
from application import app
from flask import request, redirect, g

from common.models.user import User
from common.libs.user.UserService import UserService
from common.libs.UrlManager import UrlManager
import re

@app.before_request
def before_request():
    path = request.path
    ingore_urls = app.config['IGNORE_URLS']
    ingore_check_login_urls = app.config['IGNORE_CHECK_LOGIN_URLS']
    pattern = re.compile('%s'%'|'.join(ingore_check_login_urls))
    if '/api' in path:
        return
    if pattern.match(path):
        return
    pattern = re.compile('%s' % '|'.join(ingore_urls))
    if pattern.match(path):
        return
    user_info = check_login()
    if not user_info:
        return redirect(UrlManager.buildUrl('/user/login'))

'''
判断用户是否已经登录
'''
def check_login():
    cookies = request.cookies
    auth_cookie = cookies.get(app.config.get('AUTH_COOKIE_NAME')) if cookies.get(app.config.get('AUTH_COOKIE_NAME')) else None
    if auth_cookie is None:
        return False
    auth_info = auth_cookie.split('#')
    if len(auth_info) != 2:
        return False
    try:
        user_info = User.query.filter_by(uid = auth_info[1]).first()
    except Exception:
        return False
    if not user_info:
        return False
    if '%s#%s'%(UserService.geneAuthCode(user_info), user_info.uid) != auth_cookie:
        return False
    # 将用户信息赋值给全局g变量
    g.current_user = user_info
    return user_info